package com.xpgk.xpsoft.user;


import java.io.File;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.ExceededSizeException;
import com.jfinal.upload.UploadFile;
import com.xpgk.common.controller.BaseController;
import com.xpgk.common.kit.NetKit;
import com.xpgk.common.kit.PubKit;
import com.xpgk.model.FrmUser;
import com.xpgk.xpsoft.common.XPSoftLog;
import com.xpgk.xpsoft.constants.XPSoftConstant;

public class UserController extends BaseController {

	public void index() {

		int CurUserID = getCurUserID();
		FrmUser user = UserService.getUser(CurUserID);
		if ("2".equals(user.getTYPE()))// 操作员不具备用户管理权限
		{
			renderError(404);
			return;
		}
		setAttr("bCanAdd", UserService.hasRight(CurUserID, "/xpUser/add_ui"));
		setAttr("bCanEdit", UserService.hasRight(CurUserID, "/xpUser/edit_ui"));
		render("index.html");
	}

	/**
	 * 分页查询数据
	 */
	public void pagingData() {
		int CurUserID = getCurUserID();
		FrmUser user = UserService.getUser(CurUserID);
		Kv cond = Kv.by("USERNAME like ", isParaBlank("userName") ? null : "%" + getPara("userName") + "%");
		cond.set("T.PHONE like ", isParaBlank("phone") ? null : "%" + getPara("phone", "") + "%");
		cond.set("T.NAME like", isParaBlank("name") ? null : "%" + getPara("name") + "%");
		String data = paging("xpSoftUser.findList", Kv.by("cond", cond).set("DEPARTMENTID", user.getDEPARTMENTID()));
		renderJson(data);
	}

	public void help() {
		render("help.html");
	}

	// 注：定义函数名时，如"void add()",页面的展示请以_ui结尾，void add_ui() 涉及到权限问题
	// add与add_ui有同样的权限
	public void add_ui() {
		int CurUserID = getCurUserID();
		setAttr("departmentList", Db.find(Db.getSqlPara("xpSoftUser.findDepartmentList", CurUserID)));
		int departmentID = UserService.getUser(CurUserID).getDEPARTMENTID();
		setAttr("departmentID", departmentID);
		setAttr("roleList", Db.find(Db.getSqlPara("xpSoftUser.findRoleList", CurUserID)));
		render("add.html");
	}

	// 注册
	@Before(Tx.class)
	public void add() {
		FrmUser user = getModel(FrmUser.class, "user");
		String result = UserService.saveUser(user);
		if (!result.equals("ok")) {
			renderJSONMsg(result, false);
			return;
		}
		if (user.getTYPE().equals("2"))
			UserService.updateUserRole(user.getID(), getParaValuesToInt("role"));
		XPSoftLog.write(getCurUserID(), "addUser", "role=" + user.toString(), XPSoftConstant.log_user, 1, "添加用户", NetKit.getClientIP(getRequest()));
		renderJSONMsg("注册成功.", true);
	}

	// 用户管理中用户编辑
	public void edit_ui() {
		int id = getParaToInt("ID", 0);
		FrmUser user = UserService.getUser(id);
		setAttr("departmentList", Db.find(Db.getSqlPara("xpSoftUser.findDepartmentList", getCurUserID())));
		setAttr("roleList", Db.find(Db.getSqlPara("xpSoftUser.findRoleList", id)));
		setAttr("user", user);
		setAttr("bSelf", id == getCurUserID());
		FrmUser curUser = UserService.getUser(getCurUserID());
		int departmentID = curUser.getDEPARTMENTID();
		setAttr("departmentID", departmentID);
		setAttr("bEdit", "1");
		setAttr("bResetPassword", Integer.parseInt(curUser.getTYPE()) <= 1);
		setAttr("detail", Db.findById("FRM_USER_INFO", "USERID", id));
		render("edit.html");
	}

	// 用户管理中用户编辑
	@Before(Tx.class)
	public void edit() {
		FrmUser user = getModel(FrmUser.class, "user");
		System.out.println(user.toJson());
		int userID = PubKit.toInt(user.getID(), -1);
		String result = UserService.updateUser(user);
		if (!result.equals("ok")) {
			renderJSONMsg(result, false);
			return;
		}
		UserService.updateUserRole(userID, getParaValuesToInt("role"));
		XPSoftLog.write(getCurUserID(), "editUser", "role=" + user.toString(), XPSoftConstant.log_user, 2, "修改用户信息", NetKit.getClientIP(getRequest()));
		renderJSONMsg("修改成功.", true);
	}

	//个人信息修改
	public void editDetail_ui() {
		String userName = getPara("userName");
		if (userName == null || !userName.equals(getCurUserName())) {
			renderError(404);
			return;
		}
		FrmUser user = UserService.getUser(userName);
		setAttr("user", user);
		setAttr("detail", Db.findById("FRM_USER_INFO", "USERID", user.getID()));
		render("editDetail.html");
	}

	//个人信息修改
	@Before(Tx.class)
	public void editDetail() {
		FrmUser user = getModel(FrmUser.class, "user");
		int userID = PubKit.toInt(user.getID(), -1);
		if (userID == -1 || userID != getCurUserID()) {
			renderError(404);
			return;
		}
		keepPara();
		String result = UserService.updateUser(user);
		if (!result.equals("ok")) {
			renderMsg(result, "editDetail.html");
			return;
		}
		result = UserService.updateUserDetail(GetRecord("detail"));
		if (!result.equals("ok")) {
			rollback();
			renderMsg(result, "editDetail.html");
			return;
		}
		XPSoftLog.write(getCurUserID(), "editUser", "role=" + user.toString(), XPSoftConstant.log_user, 2, "修改用户详细信息", NetKit.getClientIP(getRequest()));
		setAttr("detail", Db.findById("FRM_USER_INFO", "userID", userID));
		renderJSONMsg("修改成功.", true);
	}

	@Before(Tx.class)
	public void uploadPhoto() {
		String userName = getPara("userName");
		Kv ret;
		try {
			UploadFile file = getFile("file", "temp", 2 * 1024 * 1024, "utf-8"); // 最大上传2M的图片
			ret = UserService.setUserPhoto(userName, file);
		} catch (Exception e) {
			if (e instanceof ExceededSizeException){
				ret = Kv.by("msg", "最大上传2M的图片");
				ret.set("flag", 0);
			}
			else{
				ret = Kv.by("msg", e.toString());
				ret.set("flag", 0);
			}
		}
		setAttr("result", ret);
		renderJson();
	}
	
	@Clear
	public void changePassword_ui() {
		keepPara();
		render("changePassword.html");
	}
	
	@Clear
	@Before(Tx.class)
	public void changePassword() {
		keepPara();
		int userID = getParaToInt("ID", -1);
		if (userID == -1 || userID != getCurUserID()) {
			renderError(404);
			return;
		}
		String password1 = getPara("password1");
		String password2 = getPara("password2");
		if (password1 != null && password1.equals(password2)) {
			UserService.setPassword(getCurUserName(), password1);
			XPSoftLog.write(getCurUserID(), "changePassword", "userName=" + getCurUserName(), XPSoftConstant.log_user, 5, "修改密码", NetKit.getClientIP(getRequest()));
			renderMsg("修改成功", "changePassword.html", true);
			return;
		}
		renderMsg("两次输入的密码不一致", "changePassword.html", false);
	}

	public void resetPassword() {
		int userID = getParaToInt("id", -1);
		if (userID == -1 || -1 == getCurUserID()) {
			renderError(404);
			return;
		}
		FrmUser user = UserService.getUser(getCurUserID());
		if (user == null || (Integer.parseInt(user.getTYPE()) != 0 && Integer.parseInt(user.getTYPE()) != 1)) {
			renderError(404);
			return;
		}
		user = UserService.getUser(userID);
		if (user == null) {
			renderError(404);
			return;
		}
		UserService.setPassword(user.getUSERNAME(), HashKit.md5("888888"));
		XPSoftLog.write(getCurUserID(), "resetPassword", "userName=" + user.getUSERNAME(), XPSoftConstant.log_user, 4, "密码初始化", NetKit.getClientIP(getRequest()));
		edit_ui();
		renderMsg("修改成功.", "edit.html", true);
		return;
	}

	@Before(Tx.class)
	public void editState() {
		int id = getParaToInt("ID", 0);
		String state = getPara("state", "-1");
		if (!state.equals("-1")) {
			FrmUser user = FrmUser.dao.findById(id);
			user.setSTATE(state);
			String result = UserService.updateUser(user);
			if (!result.equals("ok")) {
				renderJSONMsg(result, false);
				return;
			}
			renderJSONMsg("修改成功.", true);
		} else {
			renderJSONMsg("修改失敗", false);
		}
	}
}
